import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

// 判断一个判断当前模块是否有权限的方法
function hasUrl(url,next){
  // 我们要判断当前地址是否在信息menu数组中，如果在就放行，如果不在就拦截，强制跳转到首页
  let result = store.getters.getUser.menus_url.some((item) => url === item);
  if(result){
    next()
  }else{
    next('/home')
  }
}

Vue.use(VueRouter)

export const IndexRouter =[
  {
    path:'/menu',
    component:() => import('../views/menu/menu.vue'),
    meta:{
      title:'菜单管理'
    },
    beforeEnter (to, from, next){
      hasUrl('/menu',next)
    }
  },
  {
    path:'/role',
    component:() => import('../views/role/role.vue'),
    meta:{
      title:'角色管理'
    },
    beforeEnter (to, from, next){
      hasUrl('/role',next)
    }
  },
  {
    path:'/user',
    component:() => import('../views/user/user.vue'),
    meta:{
      title:'管理员管理'
    },
    beforeEnter (to, from, next){
      hasUrl('/user',next)
    }
  },
  {
    path:'/cate',
    component:() => import('../views/cate/cate.vue'),
    meta:{
      title:'商品分类'
    }
  },
  {
    path:'/specs',
    component:() => import('../views/specs/specs.vue'),
    meta:{
      title:'商品规格'
    },
    beforeEnter(to,from,next){
      hasUrl('/specs',next)
    }
  },
  {
    path:'/goods',
    component:() => import ('../views/goods/goods.vue'),
    meta:{
      title:'商品管理'
    },
    beforeEnter(to,from,next){
      hasUrl('/specs',next)
    }
  },
  {
    path:'/member',
    component:() => import('../views/member/member.vue'),
    meta:{
      title:'会员管理'
    },
    beforeEnter(to,from,next){
      hasUrl('/member',next)
    }
  },
  {
    path:'/banner',
    component:() => import('../views/banner/banner.vue'),
    meta:{
      title:'轮播图管理'
    },
    beforeEnter(to,from,next){
      hasUrl('/banner',next)
    }
  },
  {
    path:'/seck',
    component:() => import('../views/seck/seck.vue'),
    meta:{
      title:'秒杀活动'
    },
    beforeEnter(to,from,next){
      hasUrl('/seck',next)
    }
  }
]

const routes = [
  {
    path:'/index',
    component:()=> import('../pages/index.vue'),
    children:[
      {
        path:'/home',
        component:() => import('../views/home.vue')
      },
      ...IndexRouter,
      { // 二级路由重定向
        path:'',
        redirect:'/home'
      }
    ]
  },
  {
    path:'/login',
    component:() => import('../pages/login.vue')
  },
  { // 一级路由重定向
    path:'*',
    redirect:'/index'
  }
]

const router = new VueRouter({
  routes
})

// 封装全局登录事件
router.beforeEach((to,from,next) => {
  // 1.先检测用户访问的地址是否是登录
  if(to.path == '/login'){
    next();
    return
  }
  // 2.判断用户是否登录
  if(store.getters.getUser){
    next();
    return
  }
  // 3.如果没登录 强制跳转到登录页面
  next('/login')
})

export default router